package com.htj.util;

import java.util.Date;
import net.sf.json.JSONObject;

public class WeChatToken {
   public static String AppID = "wx150272ef1963f321";
   private static String SEC = "ZuQ-_xuOIOkq1yreONIESmxavrcvoNYotHt7oC8dzTU";
   private static int Expires_Period = 7200;
   private static long GetAccessToken_Times = 1L;
   private static String _accessTokens = "";

   public static String get_accessToken() {
      String token = "";
      if (_accessTokens != null && !_accessTokens.toString().equals("") && !HasExpired()) {
         token = _accessTokens;
      } else {
         token = GetAccessToken(AppID, SEC);
         GetAccessToken_Times = (new Date()).getTime();
      }

      return token;
   }

   private static boolean HasExpired() {
      long time = GetAccessToken_Times;
      long nwtime = (new Date()).getTime();
      return nwtime > time + (long)(Expires_Period * 1000) - 60000L;
   }

   public static String GetAccessToken(String AppID, String AppSecret) {
      String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + AppID + "&corpsecret=" + AppSecret;
      JSONObject jsonObject = HttpUtil.httpsRequest(url, "GET", (String)null);
      if (jsonObject == null) {
         return "error token";
      } else {
         if (jsonObject.getString("expires_in") != null) {
            Expires_Period = Integer.parseInt(jsonObject.getString("expires_in"));
         }

         return jsonObject.getString("access_token");
      }
   }
}
